package com.immediatus.graphics.vertex;

import com.immediatus.graphics.font.Font;
import com.immediatus.options.Align;
import com.immediatus.util.FastFloatBuffer;

public class TextVertexBuffer extends VertexBuffer{
    public static final int VERTICES_PER_CHARACTER = 6;

    private final Align _horizontalAlign;

    public TextVertexBuffer(final int characterCount_, final Align align_, final int type_, final boolean managed_){
        super(2 * VERTICES_PER_CHARACTER * characterCount_, type_, managed_);

        this._horizontalAlign = align_;
    }

    public synchronized void update(final Font font_, final int maximumLineWidth_, final int[] width_, final String[] lines_){
        final int[] bufferData = this._BufferData;
        int i = 0;

        final int lineHeight = font_.getLineHeight();

        final int lineCount = lines_.length;
        for (int lineIndex = 0; lineIndex < lineCount; lineIndex++){
            final String line = lines_[lineIndex];

            int lineX;
            switch (this._horizontalAlign){
                case RIGHT:
                    lineX = maximumLineWidth_ - width_[lineIndex];
                    break;
                case CENTER:
                    lineX = (maximumLineWidth_ - width_[lineIndex]) >> 1;
                    break;
                case LEFT:
                default:
                    lineX = 0;
            }

            final int lineY = lineIndex * (font_.getLineHeight() + font_.getLineGap());
            final int lineYBits = Float.floatToRawIntBits(lineY);

            final int lineLength = line.length();
            for (int letterIndex = 0; letterIndex < lineLength; letterIndex++){
                final com.immediatus.graphics.font.Character ch = font_.getLetter(line.charAt(letterIndex));

                final int lineY2 = lineY + lineHeight;
                final int lineX2 = lineX + ch.getWidth();

                final int lineXBits = Float.floatToRawIntBits(lineX);
                final int lineX2Bits = Float.floatToRawIntBits(lineX2);
                final int lineY2Bits = Float.floatToRawIntBits(lineY2);

                bufferData[i++] = lineXBits;
                bufferData[i++] = lineYBits;

                bufferData[i++] = lineXBits;
                bufferData[i++] = lineY2Bits;

                bufferData[i++] = lineX2Bits;
                bufferData[i++] = lineY2Bits;

                bufferData[i++] = lineX2Bits;
                bufferData[i++] = lineY2Bits;

                bufferData[i++] = lineX2Bits;
                bufferData[i++] = lineYBits;

                bufferData[i++] = lineXBits;
                bufferData[i++] = lineYBits;

                lineX += ch.getAdvance();
            }
        }

        final FastFloatBuffer vertexFloatBuffer = this._FloatBuffer;
        vertexFloatBuffer.position(0);
        vertexFloatBuffer.put(bufferData);
        vertexFloatBuffer.position(0);

        super.setHardwareBufferNeedsUpdate();
    }
}
